function toggle_checkboxes ( node ) {
  YUI({combine: true, timeout: 150000}).use("node",
  function(Y) {
    batch = node.id.substr("checkbox-".length);
    Y.all('.sample-in-batch-' + batch).each( function(x) {
      x.set('checked', node.checked);
      if ( node.checked ) {
	x.addClass('selected');
      }
      else {
	x.removeClass('selected');
      }
    });
  });
}

function toggle_one_checkbox ( node ) {
  YUI({combine: true, timeout: 150000}).use("node",
  function(Y) {
    n = Y.one(node);
    if ( node.checked ) {
      n.addClass('selected');
    }
    else {
      n.removeClass('selected');
    }
  });
}

function hide_distance_matrix ( ) {
  YUI({combine: true, timeout: 150000}).use("node",
  function(Y) {
    container = Y.one('#matrix_container');
    container.set("innerHTML", "");
  });
}

function load_distance_matrix ( ) {
  YUI({combine: true, timeout: 150000}).use("io",
  function(Y) {
    container = Y.one('#matrix_container');

    list = new Array;
    Y.all('.selected').each( function(node) {
      list.push(node._node.id);
    });

    node = Y.one('#threshold');
    list.push('threshold=' + node._node.value);

    node = Y.one('#error');
    list.push('error=' + node._node.value);

    // A function handler to use for successful requests:
    var handleSuccess = function(ioId, o) {
      Y.log("The success handler was called.  Id: " + ioId + ".", "info", "example");
      if ( o.responseText !== undefined ) {

        if ( o.responseText.match(/^ERROR/) ) {
	    alert(o.responseText);
	  }
	  else {
	    // success
	    container.set("innerHTML", o.responseText);
	  }
      }
    }

    // A function handler to use for failed requests:
    var handleFailure = function(ioId, o) {
      Y.log("The failure handler was called.  Id: " + ioId + ".", "info", "example");

      if( o.responseText !== undefined ) {
        var s = "<li>Transaction id: " + ioId + "</li>";
           s += "<li>HTTP status: " + o.status + "</li>";
           s += "<li>Status code message: " + o.statusText + "</li>";
           alert(s);
      }
    }

    // Subscribe our handlers to IO's global custom events:
    Y.on('io:success', handleSuccess);
    Y.on('io:failure', handleFailure);

    /* Configuration object for POST transaction */
    var cfg = {
      method: "POST",
      data: list.join(';')
    };

    // send the request
    var request = Y.io("distance_matrix.html", cfg);
    container.set("innerHTML", "<img src='lib/graphics/wait20trans.gif' style='vertical-align: middle'> &nbsp; calculating ...");
    Y.log("Initiating request; Id: " + request.id + ".", "info", "example");
  });
}

function handle_key ( node, e ) {
  YUI({combine: true, timeout: 150000}).use("io",
  function(Y) {
    var key = e.keyCode || e.which;
    if (key == 13) {
      Y.log(node.id + ": " + node.value);
      node.style.backgroundImage = "url('lib/graphics/wait20trans.gif')";
      node.style.backgroundRepeat = "no-repeat";
      node.style.backgroundPosition = "right center";

      // A function handler to use for successful requests:
      var handleSuccess = function(ioId, o) {
        Y.log("The success handler was called.  Id: " + ioId + ".", "info", "example");
        if ( o.responseText !== undefined ) {

          if ( o.responseText.match(/^ERROR/) ) {
	    alert(o.responseText);
	  }
	  else {
	    // success
	    node.style.backgroundImage = "";
	  }
        }
      }

      // A function handler to use for failed requests:
      var handleFailure = function(ioId, o) {
        Y.log("The failure handler was called.  Id: " + ioId + ".", "info", "example");

        if( o.responseText !== undefined ) {
          var s = "<li>Transaction id: " + ioId + "</li>";
             s += "<li>HTTP status: " + o.status + "</li>";
             s += "<li>Status code message: " + o.statusText + "</li>";
             alert(s);
        }
      }

      // Subscribe our handlers to IO's global custom events:
      Y.on('io:success', handleSuccess);
      Y.on('io:failure', handleFailure);

      /* Configuration object for POST transaction */
      var cfg = {
        method: "GET",
           data: "key=" + node.id + ";" + "tag=" + node.value,
      };

      // send the request
      var request = Y.io("cgi/update_tag.cgi", cfg);
      Y.log("Initiating request; Id: " + request.id + ".", "info", "example");
    }
  });
}

function toggle_samples ( dir, batch_id ) {
  YUI({combine: true, timeout: 150000}).use("io",
  function(Y) {
    loading = false;

    // block multiple requests
    if (loading) {
      return;
    }
    loading = true;

    toggle = Y.one('#toggle-' + batch_id);
    if ( toggle.test('.contract') ) {
      // change the toggle icon
      toggle.set('src', 'lib/graphics/expand.png');
      toggle.removeClass('contract');
      toggle.addClass('expand');

      // expand and contract variable items
      Y.one('#pipeline-expanded-' + batch_id).setStyle('display', 'none');
      Y.all('.expanded-' + batch_id).setStyle('display', 'none');
      Y.one('#pipeline-contracted-' + batch_id).setStyle('display', 'block');
    }
    else {
      if ( 0 && loaded[batch_id] ) { // this does not work; the table layout breaks

        // just expand
        Y.all('.expanded-' + batch_id).setStyle('display', 'block');
        // ...
      }
      else {
        // Get a reference to the node that we are using
        // to attach the sample nodes:
        var header = Y.one('#header-' + batch_id);
        var parent = header.get('parentNode'); // <tbody>
        next_header = Y.get('#header-' + next_dir[batch_id]);

        // Create a temporary display node.

        // Insertion of html data is done using the old DOM interface because
        // at the moment, YUI 3 breaks trying to insert html-encoded table rows.
        next_header_DOMNode = Y.Node.getDOMNode(next_header);
        parent_DOMNode = Y.Node.getDOMNode(parent);
        temp_row = Y.Node.create("<tr id=\"temp_row\"><td colspan=\"6\"><div id=\"message\"></div></td></tr>");
        temp_row_DOMNode = Y.Node.getDOMNode(temp_row);
        parent_DOMNode.insertBefore(temp_row_DOMNode, next_header_DOMNode);
        message = Y.one('#message');

        // A function handler to use for successful requests:
        var handleSuccess = function(ioId, o) {
          Y.log("The success handler was called.  Id: " + ioId + ".", "info", "example");
          if ( o.responseText !== undefined ) {

            temp_row.remove();

            if ( ! o.responseText.match(/^NO PEAKS/) ) {
              chunks = new Array;
              regex = new RegExp("[\n ]+<!-- cut -->[\n ]+");
              chunks = o.responseText.split(regex);
              for ( i in chunks ) {
                row_html = chunks[i];
                row = Y.Node.create(row_html);
                row_DOMNode = Y.Node.getDOMNode(row);
                parent_DOMNode.insertBefore(row_DOMNode, next_header_DOMNode);
              }
            }

            // make sure we don't have to do this again
            loaded[batch_id] = 1;
          }

          // change the toggle icon
          toggle.set('src', 'lib/graphics/contract.png');
          toggle.removeClass('expand');
          toggle.addClass('contract');

          // expand and contract the variable items
          Y.one('#pipeline-expanded-' + batch_id).setStyle('display', 'block');
          Y.one('#pipeline-contracted-' + batch_id).setStyle('display', 'none');

          // cascade the batch checkbox settings
	  checkbox = Y.one('#checkbox-' + batch_id);
	  toggle_checkboxes(checkbox._node);
        }

        // A function handler to use for failed requests:
        var handleFailure = function(ioId, o) {
          Y.log("The failure handler was called.  Id: " + ioId + ".", "info", "example");

          if( o.responseText !== undefined ) {
            var s = "<li>Transaction id: " + ioId + "</li>";
               s += "<li>HTTP status: " + o.status + "</li>";
               s += "<li>Status code message: " + o.statusText + "</li>";
               message.set("innerHTML", s);
          }
        }

        // Subscribe our handlers to IO's global custom events:
        Y.on('io:success', handleSuccess);
        Y.on('io:failure', handleFailure);

        /* Configuration object for POST transaction */
        var cfg = {
          method: "POST",
             data: "directory=" + dir + "&" + "dirname=" + batch_id,
        };

        // The URL of the resource to which we're POSTing data:
        var sUrl = "batch_job.html";
        message.set("innerHTML", "<img src='lib/graphics/wait20trans.gif' style='vertical-align: middle'> &nbsp; Loading data ...");

        var request = Y.io(sUrl, cfg);
        Y.log("Initiating request; Id: " + request.id + ".", "info", "example");
      }
    }
  });
}

function launch_viewer ( directory, kind ) {
  var url = "view.html?dir=" + directory + ";kind=" + kind;
  var name = "Signal Veiwer (" + kind + ")";
  var options = "";
  child_window = window.open(url, name, options);
}

function launch_process ( directory, kind ) {
  var url;
  var name;
  if ( kind == "copy" ) {
    url = "cgi/copy.cgi?dir=" + directory;
    name = "copying files from remote directory";
  }
  if ( kind == "clip" ) {
    url = "cgi/clip.cgi?dir=" + directory;
    name = "clipping the standard ladder for warping";
  }
  if ( kind == "hist" ) {
    url = "cgi/hist.cgi?dir=" + directory;
    name = "calculating histograms";
  }
  if ( kind == "target" ) {
    url = "cgi/target.cgi?dir=" + directory;
    name = "fitting the target";
  }
  if ( kind == "warp" ) {
    url = "cgi/warp.cgi?dir=" + directory;
    name = "warping process";
  }
  if ( kind == "peaks" ) {
    url = "cgi/peaks.cgi?dir=" + directory;
    name = "Scanning for peaks";
  }
  var options = "";
  child_window = window.open(url, name, options);
}
